package com.rickpan.service;

import com.rickpan.entity.User;
import com.rickpan.entity.VipFeatureConfig;
import com.rickpan.entity.VipUsageRecord;
import com.rickpan.repository.TeamRepository;
import com.rickpan.repository.UserRepository;
import com.rickpan.repository.VipFeatureConfigRepository;
import com.rickpan.repository.VipUsageRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.PostConstruct;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * VIP功能限制服务
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VipFeatureService {

    private final VipUsageRecordRepository usageRepository;
    private final VipFeatureConfigRepository configRepository;
    private final UserRepository userRepository;
    
    @Autowired(required = false)
    private TeamRepository teamRepository;
    
    @Autowired(required = false)
    private ReportManageService reportManageService;

    /**
     * 初始化VIP功能配置
     */
    @PostConstruct
    public void initVipFeatureConfigs() {
        try {
            log.info("初始化VIP功能配置...");
            
            // AI工作报告配置
            initFeatureConfig("AI_REPORT", "AI工作报告", "使用AI生成智能工作报告", 
                30L, -1L, VipFeatureConfig.LimitPeriod.MONTHLY, 2);
            
            // 团队创建配置
            initFeatureConfig("TEAM_CREATE", "团队创建", "创建和管理团队协作", 
                3L, -1L, VipFeatureConfig.LimitPeriod.TOTAL, 1);
            
            // 优先支持配置
            initFeatureConfig("PRIORITY_SUPPORT", "优先客服支持", "享受优先技术支持服务", 
                0L, -1L, VipFeatureConfig.LimitPeriod.TOTAL, 3);
                
            log.info("VIP功能配置初始化完成");
        } catch (Exception e) {
            log.error("初始化VIP功能配置失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 初始化单个功能配置
     */
    private void initFeatureConfig(String featureCode, String featureName, String description,
                                 Long basicLimit, Long vipLimit, VipFeatureConfig.LimitPeriod limitPeriod, Integer sortOrder) {
        try {
            var existingConfig = configRepository.findByFeatureCode(featureCode);
            if (existingConfig.isEmpty()) {
                VipFeatureConfig config = new VipFeatureConfig();
                config.setFeatureCode(featureCode);
                config.setFeatureName(featureName);
                config.setFeatureDescription(description);
                config.setBasicLimit(basicLimit);
                config.setVipLimit(vipLimit);
                config.setLimitPeriod(limitPeriod);
                config.setIsActive(true);
                config.setSortOrder(sortOrder);
                
                configRepository.save(config);
                log.info("创建VIP功能配置: {} - {}", featureCode, featureName);
            } else {
                // 更新现有配置，确保限制值是最新的
                VipFeatureConfig config = existingConfig.get();
                if (!config.getBasicLimit().equals(basicLimit)) {
                    config.setBasicLimit(basicLimit);
                    configRepository.save(config);
                    log.info("更新VIP功能配置: {} - 基础限制更新为: {}", featureCode, basicLimit);
                }
            }
        } catch (Exception e) {
            log.warn("初始化功能配置失败: {} - {}", featureCode, e.getMessage());
        }
    }

    /**
     * 检查用户是否可以使用某功能
     */
    @Transactional(readOnly = true)
    public boolean canUseFeature(Long userId, String featureCode) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return false;
        }

        // VIP用户大部分功能无限制
        if (user.isVip()) {
            return true;
        }

        // BASIC用户检查使用限制
        VipFeatureConfig config = configRepository.findByFeatureCode(featureCode).orElse(null);
        if (config == null || !config.getIsActive()) {
            return false; // 功能不存在或未启用
        }

        // -1表示禁用，0表示无限制
        if (config.getBasicLimit() == -1) {
            return false; // BASIC用户禁用此功能
        }
        if (config.getBasicLimit() == 0) {
            return true; // 无限制
        }

        // 检查当前使用量
        int currentUsage = getCurrentUsage(userId, featureCode, config.getLimitPeriod());
        return currentUsage < config.getBasicLimit();
    }

    /**
     * 记录功能使用
     */
    @Transactional
    public void recordFeatureUsage(Long userId, String featureCode) {
        recordFeatureUsage(userId, featureCode, 1, null);
    }

    /**
     * 记录功能使用（带使用次数和详情）
     */
    @Transactional
    public void recordFeatureUsage(Long userId, String featureCode, int usageCount, String usageDetails) {
        LocalDate today = LocalDate.now();

        Optional<VipUsageRecord> existingRecord = usageRepository
            .findByUserIdAndFeatureCodeAndUsageDate(userId, featureCode, today);

        if (existingRecord.isPresent()) {
            // 增加使用次数
            VipUsageRecord record = existingRecord.get();
            record.setUsageCount(record.getUsageCount() + usageCount);
            if (usageDetails != null) {
                record.setUsageDetails(usageDetails);
            }
            usageRepository.save(record);
        } else {
            // 创建新记录
            VipUsageRecord record = new VipUsageRecord();
            record.setUserId(userId);
            record.setFeatureCode(featureCode);
            record.setUsageDate(today);
            record.setUsageCount(usageCount);
            record.setUsageDetails(usageDetails);
            usageRepository.save(record);
        }

        log.debug("记录用户 {} 功能 {} 使用量: {}", userId, featureCode, usageCount);
    }

    /**
     * 获取用户功能使用统计
     */
    @Transactional(readOnly = true)
    public List<FeatureUsageVO> getUserFeatureUsages(Long userId) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return new ArrayList<>();
        }

        List<VipFeatureConfig> activeConfigs = configRepository.findByIsActiveTrueOrderBySortOrder();
        List<FeatureUsageVO> usages = new ArrayList<>();

        // 定义项目中实际存在的功能
        List<String> existingFeatures = List.of(
            "STORAGE",        // 存储空间
            "AI_REPORT",      // AI工作报告  
            "TEAM_CREATE",    // 团队创建
            "PRIORITY_SUPPORT" // 优先支持
        );

        for (VipFeatureConfig config : activeConfigs) {
            // 过滤掉不存在的功能
            if (!existingFeatures.contains(config.getFeatureCode())) {
                continue;
            }

            // 跳过存储空间功能，它在别的地方单独显示
            if ("STORAGE".equals(config.getFeatureCode())) {
                continue;
            }

            // VIP用户只显示有限制的功能
            if (user.isVip() && config.getVipLimit() == -1) {
                continue;
            }

            // BASIC用户显示所有相关功能
            if (!user.isVip() && config.getBasicLimit() <= 0) {
                continue; // 禁用功能或VIP专享功能不显示给基础用户
            }

            int currentUsage = getCurrentUsage(userId, config.getFeatureCode(), config.getLimitPeriod());
            long limit = user.isVip() ? config.getVipLimit() : config.getBasicLimit();

            FeatureUsageVO usage = new FeatureUsageVO();
            usage.setFeatureCode(config.getFeatureCode());
            usage.setFeatureName(config.getFeatureName());
            usage.setUsed(currentUsage);
            usage.setLimit(limit);
            usage.setLimitPeriod(config.getLimitPeriod().getDescription());
            
            if (limit > 0) {
                usage.setPercentage((currentUsage * 100.0) / limit);
                usage.setStatus(usage.getPercentage() >= 90 ? "exception" : 
                               usage.getPercentage() >= 70 ? "warning" : "success");
            } else {
                usage.setPercentage(0.0);
                usage.setStatus("success");
            }

            usages.add(usage);
        }

        return usages;
    }

    /**
     * 获取剩余使用量
     */
    @Transactional(readOnly = true)
    public int getRemainingUsage(Long userId, String featureCode) {
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            return 0;
        }

        if (user.isVip()) {
            return Integer.MAX_VALUE; // VIP用户无限制
        }

        VipFeatureConfig config = configRepository.findByFeatureCode(featureCode).orElse(null);
        if (config == null) {
            return 0;
        }

        if (config.getBasicLimit() == -1) {
            return 0; // 禁用
        }
        if (config.getBasicLimit() == 0) {
            return Integer.MAX_VALUE; // 无限制
        }

        int currentUsage = getCurrentUsage(userId, featureCode, config.getLimitPeriod());
        return Math.max(0, (int) (config.getBasicLimit() - currentUsage));
    }

    /**
     * 获取所有功能配置
     */
    @Transactional(readOnly = true)
    public List<VipFeatureConfig> getAllFeatureConfigs() {
        return configRepository.findAllByOrderBySortOrder();
    }

    /**
     * 获取当前使用量
     */
    private int getCurrentUsage(Long userId, String featureCode, VipFeatureConfig.LimitPeriod limitPeriod) {
        // 团队创建功能直接从teams表查询
        if ("TEAM_CREATE".equals(featureCode)) {
            return getTeamCreatedCount(userId);
        }
        
        // AI工作报告功能直接从报告表查询
        if ("AI_REPORT".equals(featureCode)) {
            return getAiReportCount(userId);
        }
        
        LocalDate today = LocalDate.now();
        
        return switch (limitPeriod) {
            case DAILY -> usageRepository.sumTodayUsageByUserAndFeature(userId, featureCode, today);
            case MONTHLY -> usageRepository.sumMonthlyUsageByUserAndFeature(
                userId, featureCode, today.getYear(), today.getMonthValue());
            case YEARLY -> usageRepository.sumUsageByUserAndFeatureAndDateRange(
                userId, featureCode, LocalDate.of(today.getYear(), 1, 1), today);
            case TOTAL -> usageRepository.sumUsageByUserAndFeatureAndDateRange(
                userId, featureCode, LocalDate.of(2020, 1, 1), today);
        };
    }
    
    /**
     * 获取用户创建的团队数量
     */
    private int getTeamCreatedCount(Long userId) {
        if (teamRepository != null) {
            try {
                return (int) teamRepository.countByCreatorId(userId);
            } catch (Exception e) {
                log.warn("无法获取团队创建数量: {}", e.getMessage());
            }
        }
        return 0;
    }
    
    /**
     * 获取用户创建的AI工作报告数量
     */
    private int getAiReportCount(Long userId) {
        if (reportManageService != null) {
            try {
                var stats = reportManageService.getReportStats(userId);
                return Math.toIntExact(stats.getTotalReports());
            } catch (Exception e) {
                log.warn("无法获取AI工作报告数量: {}", e.getMessage());
            }
        }
        return 0;
    }

    /**
     * 清理过期的使用记录
     */
    @Transactional
    public void cleanupExpiredRecords() {
        // 删除90天前的记录
        LocalDate cutoffDate = LocalDate.now().minusDays(90);
        int deletedCount = usageRepository.deleteExpiredRecords(cutoffDate);
        
        if (deletedCount > 0) {
            log.info("清理了 {} 条过期的功能使用记录", deletedCount);
        }
    }

    /**
     * 功能使用统计VO
     */
    public static class FeatureUsageVO {
        private String featureCode;
        private String featureName;
        private int used;
        private long limit;
        private String limitPeriod;
        private double percentage;
        private String status; // success, warning, exception

        // Getters and Setters
        public String getFeatureCode() { return featureCode; }
        public void setFeatureCode(String featureCode) { this.featureCode = featureCode; }

        public String getFeatureName() { return featureName; }
        public void setFeatureName(String featureName) { this.featureName = featureName; }

        public int getUsed() { return used; }
        public void setUsed(int used) { this.used = used; }

        public long getLimit() { return limit; }
        public void setLimit(long limit) { this.limit = limit; }

        public String getLimitPeriod() { return limitPeriod; }
        public void setLimitPeriod(String limitPeriod) { this.limitPeriod = limitPeriod; }

        public double getPercentage() { return percentage; }
        public void setPercentage(double percentage) { this.percentage = percentage; }

        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
    }
}